var connect = require('connect');
var http = require('http');
var router = require('./middleware/router');
//日志中间件v1
function logger(req, res, next) {
    console.log("%s %s", req.method, req.url);
    next();
}
//日志中间件v2,可以配置
//这种闭包即使函数返回了一样可以访问到options  ':method :url'可以自定义返回格式
function logger2(options) {
    return function(req, res, next) {
        var regexp = /:(\w+)/g;
        var str = options.replace(regexp, function(match, property) {
            return req[property];
        });
        console.log(str);
        next();
    };
}
//简单的basic认证
/**
GET /admin HTTP/1.1
Host: 127.0.0.1:3090
Authorization: Basic YWRtaW46MTIz
Cache-Control: no-cache
Postman-Token: 79893129-fa26-d5f1-9cca-af390307c5e0
 */
function restrict(req, res, next) {
    var authorization = req.headers['authorization'];
    if (authorization) {
        var parts = authorization.split(' ');
        var schema = parts[0];
        var author = new Buffer(parts[1], 'base64').toString().split(':');
        var user = author[0];
        var psd = author[1];
        if (user === 'admin' && psd === '123') {
            next();
        }
    } else {
        next(new Error('Unauthorized'));
    }
}
//主要处理
function main(req, res) {
    res.end('hello welcome to our team');
}
//自定义错误处理
function errorHandler() {
    var env = process.env.NODE_ENV || 'development';
    return function(err, req, res, next) {
        
        res.statusCode = 500;
        switch (env) {
            case 'development':
                res.setHeader('Content-Type', 'application/json');
                res.end(err.stack);
                break;
            default:
                res.end('Server error'+err.message);
        }
    }
}
var routes = {
    "GET": {
        '/getuser/:id': function(req, res) {
            res.end('I am god');
        }
    }
};

//多个错误处理
function UserErrorHandler(){
    return function(err, req, res, next){
        res.setHeader('Content-Type','application/json');
        res.statusCode = 500;
        res.end('err '+ err.message);
    }
}
var user = connect().use(function(req, res){
    res.end(wtf());
}).use(UserErrorHandler());

function MyError(message) {
  this.name = 'MyError';
  this.message = message || 'Default Message';
  this.stack = (new Error()).stack;
}
MyError.prototype = Object.create(Error.prototype);
MyError.prototype.constructor = MyError;

var app = connect();
app.use(logger2(':method :url'))
    .use('/admin', restrict) //访问admin的资源需要认证
    .use('/admin', main)
    .use('/api/v1', router(routes))
    .use('/error', function(req,res){
        var t = shutup();
        res.end('this is error page' + t);
    })
    .use('/error',function(err,req,res,next){
        res.end('error/ has err: '+ err.stack);
    })
    .use('/user',user)
    .use('/x5',function(req,res,next){
        next(new MyError());
    })
    .use(errorHandler());
var server = http.createServer(app);
server.listen(3090, function(err) {
    if (!err) {
        console.log('server start on port 3090');
    }
});